package com.app.couponsharelife.ui.view

import android.content.Context
import android.text.Html
import android.text.TextUtils
import android.util.AttributeSet
import android.view.Gravity
import android.view.ViewTreeObserver
import android.view.animation.AnimationUtils
import android.widget.TextView
import android.widget.ViewFlipper
import com.app.couponsharelife.R
import com.app.couponsharelife.utils.AppUtils
import java.util.ArrayList

/**
 *Created by xct on 2018/12/22
 *Description:
 */
class MarqueeView(context: Context, attrs: AttributeSet): ViewFlipper(context,attrs) {
    private var notices: ArrayList<String>? = null
    private var isSetAnimDuration = false
    private var onItemClickListener: OnItemClickListener? = null

    private var interval = 2000
    private var animDuration = 500
    private var textSize = 14
    private var textColor = -0x1

    private var singleLine = false
    private var gravity = Gravity.LEFT or Gravity.CENTER_VERTICAL
    private val TEXT_GRAVITY_LEFT = 0
    private val TEXT_GRAVITY_CENTER = 1
    private val TEXT_GRAVITY_RIGHT = 2
    init {
        val typedArray = getContext().obtainStyledAttributes(attrs,
                R.styleable.MarqueeView)
        interval = typedArray.getInteger(
                R.styleable.MarqueeView_mvInterval, interval)
        isSetAnimDuration = typedArray
                .hasValue(R.styleable.MarqueeView_mvAnimDuration)
        singleLine = typedArray.getBoolean(
                R.styleable.MarqueeView_mvSingleLine, false)
        animDuration = typedArray.getInteger(
                R.styleable.MarqueeView_mvAnimDuration, animDuration)
        if (typedArray.hasValue(R.styleable.MarqueeView_mvTextSize)) {
            textSize = typedArray.getDimension(
                    R.styleable.MarqueeView_mvTextSize, textSize.toFloat()).toInt()
            textSize = AppUtils.px2sp(context, textSize.toFloat())
        }
        textColor = typedArray.getColor(
                R.styleable.MarqueeView_mvTextColor, textColor)
        val gravityType = typedArray.getInt(
                R.styleable.MarqueeView_mvGravity, TEXT_GRAVITY_LEFT)
        when (gravityType) {
            TEXT_GRAVITY_CENTER -> gravity = Gravity.CENTER
            TEXT_GRAVITY_RIGHT -> gravity = Gravity.RIGHT or Gravity.CENTER_VERTICAL
        }
        typedArray.recycle()

        setFlipInterval(interval)

        val animIn = AnimationUtils.loadAnimation(context,
                R.anim.anim_marquee_in)
        if (isSetAnimDuration)
            animIn.duration = animDuration.toLong()
        inAnimation = animIn

        val animOut = AnimationUtils.loadAnimation(context,
                R.anim.anim_marquee_out)
        if (isSetAnimDuration)
            animOut.duration = animDuration.toLong()
        outAnimation = animOut
    }
    // 根据公告字符串启动轮播
    fun startWithText(notice: String) {
        if (TextUtils.isEmpty(notice))
            return
        viewTreeObserver.addOnGlobalLayoutListener(
                object : ViewTreeObserver.OnGlobalLayoutListener {
                    override fun onGlobalLayout() {
                        viewTreeObserver
                                .removeGlobalOnLayoutListener(this)
                        startWithFixedWidth(notice, width)
                    }
                })
    }

    // 根据公告字符串列表启动轮播
    fun startWithList(notices: List<String>) {
        setNotices(notices)
        start()
    }

    // 根据宽度和公告字符串启动轮播
    private fun startWithFixedWidth(notice: String, width: Int) {
        val noticeLength = notice.length
        val dpW = AppUtils.px2dip(context, width.toFloat())
        val limit = dpW / textSize
        if (dpW == 0) {
            throw RuntimeException("Please set MarqueeView width !")
        }

        if (noticeLength <= limit) {
            notices!!.add(notice)
        } else {
            val size = noticeLength / limit + if (noticeLength % limit != 0) 1 else 0
            for (i in 0 until size) {
                val startIndex = i * limit
                val endIndex = if ((i + 1) * limit >= noticeLength)
                    noticeLength
                else
                    (i + 1) * limit
                notices!!.add(notice.substring(startIndex, endIndex))
            }
        }
        start()
    }

    fun stop() {
        stopFlipping()
    }

    // 启动轮播
    fun start(): Boolean {
        if (notices == null || notices!!.size == 0)
            return false
        stop()
        removeAllViews()

        for (i in notices!!.indices) {
            val textView = createTextView(notices!!.get(i), i)
            textView.setOnClickListener {
                if (onItemClickListener != null) {
                    onItemClickListener!!.onItemClick(i, textView)
                }
            }
            addView(textView)
        }

        if (notices!!.size > 1) {
            startFlipping()
        }
        return true
    }

    // 创建ViewFlipper下的TextView
    private fun createTextView(text: String, position: Int): TextView {
        val tv = TextView(context)
        tv.gravity = gravity
        tv.text = Html.fromHtml(text)
        tv.setTextColor(textColor)
        tv.textSize = textSize.toFloat()
        tv.setSingleLine(singleLine)
        tv.tag = position
        return tv
    }

    fun getPosition(): Int {
        return currentView.tag as Int
    }

    fun getNotices(): List<String> {
        return notices!!
    }

    fun setNotices(notices: List<String>) {
        this.notices = notices as ArrayList<String>
    }

    fun setOnItemClickListener(onItemClickListener: OnItemClickListener) {
        this.onItemClickListener = onItemClickListener
    }

    interface OnItemClickListener {
        fun onItemClick(position: Int, textView: TextView)
    }
}